<?php
namespace Mapi\Controller;
use Mapi\Controller\BaseController;

class ArticleController extends BaseController {
    protected static $apiUrl = 'http://mobile.appwuhan.com/helper/';
	private $token = '';
	private $rotate = 0;


	public function __construct() {
		parent::__construct();
		
		$this->getToken();
	}

	/**
	 * 获取token
	 * @return [type] [description]
	 */
	protected function getToken() {
		$authUrl = self::$apiUrl . 'auth.php';

		$data['username'] = 'phptest';
		$data['password'] = '123456';
        $info = gethttpcurl($authUrl, array('postarr' => $data));
        $json = json_decode($info, true);

        $this->token = $json[0]['token'];
	}



	public function createArticle() {   
		if(IS_POST) {
			apigetpost();
			// $token = I('post.userToken'); // userToken
			// $token = '281c9830de5da1a4048ae9fe06f13673';
			$dataGet['user_id'] = $this->uid;  // 用户ID
			$dataGet['title'] = I('post.title', ''); // 文稿标题
			$dataGet['author'] = I('post.author', ''); // 文稿作者
			$dataGet['content'] = I('post.content', ''); // 文稿内容
			$dataGet['create_time'] = time();
			$dataGet['update_time'] = time();
			$dataGet['column_id'] = 1;
			if(I('post.hasAttchment')==1){ // 1-有附件   0-无附件，state字段的值为0
				$dataGet['state'] = -1;
			}elseif(I('post.hasAttchment')==0){ // 1-有附件   0-无附件，state字段的值为0
				$dataGet['state'] = 0;
			}
			$articleModel = D('Article');
			if($articleModel->create($dataGet)) {
				$res = $articleModel->add($dataGet);
				if($res) {
					$message['resultCode'] = 0;
					$message['message'] = '文档添加成功';
					$message['articleId'] = $res;		 // 文稿ID		
				} else {
					$message['resultCode'] = 1;
					$message['message'] = '文档添加失败';	
				}
			} else {
				$message['resultCode'] = 1;
				$message['message'] = $articleModel->getError();			
			}

			$this->ajaxReturn($message);			
		} else {
			$message['resultCode'] = 1;
			$message['message'] = '请求类型错误';
			$this->ajaxReturn($message);
		}
	}


	public function uploadVideo(){
		$this->uploadify('Video');
	}


	/**
	 * 上传图片
	 * @param  string $type 上传类型
	 * @return [type]       [description]
	 */
	public function uploadify($type = 'Image') {

		apigetpost();
		/*$this->ajaxReturn($_FILES);
		exit();*/
		if(IS_POST) {
		    //$file = '20160516144019.18.1.90.jpg';	
			$file = $_FILES['Filedata']['name'];
			$file = explode('.', $file);

			$this->rotate=$file[3];
			$info = $this->_uploadAttach($type,true);			
			
			
			if(is_array($info['Filedata']) && !empty($info['Filedata'])) {
				$info = $info['Filedata'];
				$dataGet['filename'] = $info['savename'];
				$dataGet['filetype'] = $info['type'];
				$dataGet['oriwidth'] = $info['oriWidth'];
				$dataGet['oriheight'] = $info['oriHeight'];
				$dataGet['thumbwidth'] = $info['thumbWidth'];
				$dataGet['thumbheight'] = $info['thumbHeight'];
				$dataGet['filesize'] = formatBytes($info['size']);
				$dataGet['filepath'] = $info['savepath'];
				$dataGet['thumb'] = $info['thumb'];
				$dataGet['uploadtime'] = time();
				$dataGet['aid'] = $file[1];
				$dataGet['sort'] = $file[2];
				$dataGet['ip'] = get_client_ip();
				//$attchmentType=$type;
				$dataGet['type'] = strtolower($type);

				$res = M('Attachment')->add($dataGet);
				if(!$res) {
					$message['resultCode'] = 1;
					$message['message'] = '上传失败，请重试';	
				} else {
					/*if(in_array($info['ext'], array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'))) {
						M('Article')->where(array('id' => $file[1]))->save(array('is_video' => 1));
					}*/
					$this->updateAttachByAid($file[1], $res);
					switch($type){
						case "Image":
							M('Article')->where('id = ' . $file[1] . ' AND indexpic = ""')->save(array('indexpic' => $info['thumb']));
						break;
						case "Video":
							M('Article')->where('id = ' . $file[1] )->save(array('indexpic' => $info['thumb']));
						break;
					}
					$message['resultCode'] = 0;
					$message['message'] = '';
					$message['attachid'] = $res;	
					$message['articleid'] = $file[1];		
				}

			} else {
				$message['resultCode'] = 1;
				$message['message'] = $info;				
			}

			$this->ajaxReturn($message);	
		}

		$this->display('createArticle');
	}

	/**
	 * 更新附件所关联的文章ID
	 * @param  [type] $articleId [description]
	 * @param  [type] $attachId  [description]
	 * @return [type]            [description]
	 */
	public function updateAttachByAid($articleId, $attachId) {
		$res = M('Attachment')->where(array('attachid' => $attachId))->save(array('aid' => $articleId));
		return $res;
	}

	/**
	 * 推送文章
	 * @return [type] [description]
	 */
	public function pushArticle($articleId) {
		// $articleId = I('get.articleId', 0);
		$info = M('Article')->where(array('id' => $articleId))->find();
		if(!$info) {
			$message['resultCode'] = 1;
			$message['message'] = '文章不存在';
			$this->ajaxReturn($message);
		}

		$fileList = M('Attachment')->where(array('aid' => $articleId))->order('sort ASC')->select(); // 文件列表
		foreach($fileList as $key=>$val) {
			$uploadUrl = self::$apiUrl . 'uploadAttach.php';
			$data['access_token'] = $this->token;
			$data['Filedata'] = '@' . I('server.DOCUMENT_ROOT') . '/Uploads/' . $val['filepath'] . $val['filename'];
			$fileinfo = gethttpcurl($uploadUrl, array('postarr' => $data));
			$fileinfo = json_decode($fileinfo, true);
			$ids[$val['attachid']] = $fileinfo[0];
			if($key==0)
				$indexpic = $fileinfo[0]['id']; 
		}

		foreach($ids as $val) {
			$info['content'] = '<img imageid="' . $val['id'] . '" src="' . $val['path'] . $val['dir'] . $val['filename'] . '" />' . $info['content'];
		}

		
		$article['title'] = $info['title'];
		$article['subtitle'] =  $info['subtitle'];
		$article['keywords'] = $info['keywords'];
		$article['author'] = $info['author'];
		$article['brief'] = $info['brief'];
		$article['content'] = $info['content'];
		$article['indexpic'] = $indexpic;
		$article['column_id'] = '135';	
		$article['access_token'] = $this->token;

		$arts = gethttpcurl(self::$apiUrl . 'createContent.php', array('postarr' => $article));
		$arts = json_decode($arts, true);
		if($arts) {
			$message['resultCode'] = 0;
			$message['message'] = '';
			$message['fileList'] = $arts;
		} else {
			$message['resultCode'] = 1;
			$message['message'] = '推送失败';		
		}

		//$this->ajaxReturn($message);
		return $message;
	}

	protected  function get_video_orientation($video_path) {
	    $cmd =  "/usr/bin/ffprobe " . $video_path . " -show_streams 2>/dev/null";
	    $result = shell_exec($cmd);
	 
	    $orientation = 0;
	    if(strpos($result, 'TAG:rotate') !== FALSE) {
	        $result = explode("\n", $result);
	        foreach($result as $line) {
	            if(strpos($line, 'TAG:rotate') !== FALSE) {
	                $stream_info = explode("=", $line);
	                $orientation = $stream_info[1];
	            }
	        }
	    }
	    return $orientation;
	}

	/**
	 * 上传附件
	 * @return [type] [description]
	 */
	protected function _uploadAttach($type, $thumb = false) {
		$ext_arr = array(
                'Image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
                'Photo' => array('jpg', 'jpeg', 'png'),
                'Flash' => array('swf', 'flv'),
                'MobileFlash' => array('mp4', 'avi', 'mov'), 
                'Video' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb','mp4', 'mov'),
                'File' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2','pdf')
        );
    
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 0 ;// 设置附件上传大小
        $saveRule=$upload->saveRule = date('ymdHis', time()) . '_' . mt_rand(5);
        $upload->autoSub = true;//使用子目录保存上传文件
        $upload->subType = 'custom';//使用日期模式创建子目录
        $upload->subName = date('Y') . '/' . date('m') . '/' . date('d');
        $upload->dateFormat = 'Ymd';//设置子目录日期格式
        $upload->allowExts  = $ext_arr[$type];// 设置附件上传类型
        $upload->rootPath  =  UPLOAD_PATH;
        $upload->savePath =  $type . '/';// 设置附件上传目录
        $upload->thumb = $thumb; //生成缩略图
        $upload->thumbMaxWidth = C('THUMB_MAX_WIDTH'); //缩略图最大宽度
        $upload->thumbMaxHeight = C('THUMB_MAX_HEIGHT'); //缩略图最大高度
        $upload->thumbRemoveOrigin = true;
    
        // 上传文件
        $info   =   $upload->upload();

        if(!$info) {        	
		   return $upload->getError();
        }else{
        	if($thumb && strtolower($type)=='image'){
        		$image = new \Think\Image(); 
        		
        		$image->open($upload->rootPath.$info['Filedata']['savepath'].$info['Filedata']['savename']);
        		$info['Filedata']['oriWidth']=$image->width(); 
        		$info['Filedata']['oriHeight']=$image->height();
        		$filename=explode(".",$info['Filedata']['savename']);
				$filename=$filename[0];
        		$info['Filedata']['thumb']=$info['Filedata']['savepath'].$filename.'_thumb.jpg';
        		$image->thumb(C('THUMB_MAX_WIDTH'), C('THUMB_MAX_HEIGHT'),1)->save($upload->rootPath.$info['Filedata']['thumb']); 
        		$info['Filedata']['thumbWidth']=$image->width(); 
        		$info['Filedata']['thumbHeight']=$image->height();   		
        	}else if($thumb && strtolower($type)=='video'){
        		extension_loaded ('ffmpeg');
    			$movefile = realpath(UPLOAD_PATH)."/".$info['Filedata']['savepath'].$info['Filedata']['savename']; 
    			$filename=explode(".",$info['Filedata']['savename']);
				$filename=$filename[0];
				$mov = new \ffmpeg_movie($movefile);
				$info['Filedata']['oriWidth']=$mov->getFrameWidth();
        		$info['Filedata']['oriHeight']=$mov->getFrameHeight();

				$f = $mov->getFrame(5);
				$gd_image = $f->toGDImage();
				$info['Filedata']['thumb']=$info['Filedata']['savepath'].$filename.'_thumb.jpg';

				if ($this->rotate==90) {
				    $gd_image = imagerotate($gd_image, 360-$this->rotate, 0);
				}

				/*if($info['Filedata']['oriWidth']>$info['Filedata']['oriHeight']){
					$gd_image = imagerotate($gd_image, 360-90, 0);
				}*/
				imagepng($gd_image, UPLOAD_PATH.$info['Filedata']['savepath'].$filename.'_thumb.png');
				imagedestroy($gd_image);
				$image = new \Think\Image(); 
				$image->open(UPLOAD_PATH.$info['Filedata']['savepath'].$filename.'_thumb.png');
				$image->thumb(C('THUMB_MAX_WIDTH'), C('THUMB_MAX_HEIGHT'),1)->save(UPLOAD_PATH.$info['Filedata']['thumb']); 
				$info['Filedata']['thumbWidth']=$image->width(); 
        		$info['Filedata']['thumbHeight']=$image->height();
        	}
		   return $info;
        }

	}

	/**
	 * 更新附近的排列位置
	 * @return [type] [description]
	 */
	public function updateAttachSort() {
		apigetpost();
		$attId = intval(I('post.attId'));
		$sortId = I('post.sortId', 0);

		if(!$attId) {
			$message['resultCode'] = 1;
			$message['message'] = '附件ID未知';
			$this->ajaxReturn($message);
		}

		$res = M('Attachment')->where(array('attachid' => $attId))->save(array('sort' => $sortId));

		if($res !== false) {
			$message['resultCode'] = 0;
			$message['message'] = '更新成功';
			$this->ajaxReturn($message);			
		} else {
			$message['resultCode'] = 1;
			$message['message'] = '更新失败';
			$this->ajaxReturn($message);
		}	
	}

	/**
	 * 删除已上传的附件列表
	 * @return [type] [description]
	 */
	public function delUploadedAttach() {
		apigetpost();
		$attIds = I('post.attIds');

		if(!$attIds) {
			$message['resultCode'] = 1;
			$message['message'] = '删除ID不能为空';
			$this->ajaxReturn($message);
		}

		$map['attachid'] = array('in', $attIds);
		$attachInfo = M('Attachment')->field('aid, filetype')->where($map)->find();
		$res = M('Attachment')->where($map)->save(array('aid' => 0));
		if($res != false) {
			$flashType = array('video/mp4', 'video/x-msvideo', 'video/quicktime');
			if(in_array($attachInfo['filetype'], $flashType)) {
				M('Article')->where(array('id' => $attachInfo['aid']))->save(array('is_video' => 0));
			}

			$message['resultCode'] = 0;
			$message['message'] = '更新成功';
			$this->ajaxReturn($message);			
		} else {
			$message['resultCode'] = 1;
			$message['message'] = '更新失败';
			$this->ajaxReturn($message);
		}			

	}

	/**
	 * 更新上传稿件纪录
	 * @return [type] [description]
	 */
	public function updateArticheById() {
		apigetpost();
		$dataGet['articleId'] = intval(I('post.articleId'));
		$dataGet['title'] = I('post.title');
		$dataGet['content'] = I('post.content');
		$dataGet['author'] = I('post.author');

		if(!$dataGet['articleId']) {
			$message['resultCode'] = 1;
			$message['message'] = '文稿ID未知';
			$this->ajaxReturn($message);
		}

		if(I('post.hasAttchment') == 1){ // 1-有附件   0-无附件，state字段的值为0
			$dataGet['state'] = -1;
		}elseif(I('post.hasAttchment') == 0){ // 1-有附件   0-无附件，state字段的值为0
			$dataGet['state'] = 0;
		}

		$res = M('Article')->where(array('id' => $dataGet['articleId'], 'user_id' => $this->uid))->save($dataGet);
		if($res !== false) {
			$message['resultCode'] = 0;
			$message['message'] = '更新成功';
			$this->ajaxReturn($message);			
		} else {
			$message['resultCode'] = 1;
			$message['message'] = '更新失败';
			$this->ajaxReturn($message);
		}

	}

	/**
	 * 根据文稿状态类型获取待查看的提醒
	 * @return [type] [description]
	 */
	public function getWarnList() {
		$waitApprovalTime = I('get.waitTime',time());
		$doingApprovalTime = I('get.doingTime',time());
		$rejectApprovalTime = I('get.rejectTime',time());
		$passApprovalTime = I('get.passTime',time());	

		try {
		   $model = M('Article');
		   $map['user_id'] = $this->uid;
		   $map['deletetime']= array('exp', 'is NULL');

		   $map['state'] = 0;
		   $map['update_time'] = array('gt',$waitApprovalTime);		   
		   $waitApprovalCount = $model->where($map)->count();
		   // echo $model->getLastsql();exit;

		   $map['state'] = 1;
		   $map['update_time'] = array('gt',$passApprovalTime);
		   $passApprovalCount = $model->where($map)->count();

		   $map['state'] = 2;
		   $map['update_time'] = array('gt',$doingApprovalTime);
		   $doingApprovalCount = $model->where($map)->count();

		   $map['state'] = 3;
		   $map['update_time'] = array('gt',$rejectApprovalTime);
		   $rejectApprovalCount = $model->where($map)->count();

			$message['resultCode'] = 0;
			$message['message'] = '';
			$message['waitApprovalCount'] = $waitApprovalCount;
			$message['passApprovalCount'] = $passApprovalCount;
			$message['doingApprovalCount'] = $doingApprovalCount;
			$message['rejectApprovalCount'] = $rejectApprovalCount;
			$this->ajaxReturn($message);

		} catch(\Exception $e) {
			$message['resultCode'] = 1;
			$message['message'] = '服务器端异常';
			$this->ajaxReturn($message);
		}

	}

	public function getOwnerArticleList() {		
		$status = I('get.status', 4);
		$pageSize = I('get.pageSize', 10);
		$hots = C('UPLOAD_HOST');
		C('VAR_PAGE', 'page');
	
		$channel = M('Channel')->field('chid, relation')->select();
		$chids = array();
		foreach($channel as $val) {
			$val['relation'] && $val['relation'] = unserialize($val['relation']);
			if(in_array($this->uid, $val['relation'][0])) {

				$chids[] = $val['chid'];			
			}		
		}

		// 如果用户有权限则返回待审和待审中的，否则只返回自己的
		if(empty($chids)) {
			switch ($status) {
				case 0:
					$map['state'] = 0;
					break;
				case 1:
					$map['state'] = 1;
					break;
				case 2:
					$map['state'] = 2;
					break;
				case 3:
					$map['state'] = 3;
					break;
				case 4:
					$map['state'] = array('neq',-1);
					break;															
			}

			$map['user_id'] = $this->uid;
			$map['deletetime'] = array('exp', 'is NULL');			
		} else {
			switch ($status) { //审核文稿状态  0-待审核 1-审核通过 2-审核中 3-退稿
				case 0:
					$map['state'] = 0;
					break;
				case 1:
					$map['state'] = 1;
					break;
				case 2:
					$map['state'] = 2;
					break;
				case 3:
					$map['state'] = 3;
					break;
				case 4:
					$map['state'] = array('neq',-1);
					break;
													
			}
			$map['deletetime'] = array('exp', 'is NULL');	
			/*$map['column_id'] = array('in', $chids);
			$map['_logic'] = 'AND';

			$map2['user_id'] = $uid;
			$map2['_complex'] = $map;
			$map2['_logic'] = 'OR';

			$map3['deletetime'] = array('exp', 'is NULL');
			$map3['_complex'] = $map2;
			$map3['_logic'] = 'AND';*/

/*			$map4['state'] = array('neq', '-1');
			$map4['_complex'] = $map3;
			$map4['_logic'] = 'AND';*/
		}
		
	
		$model = M('Article');
		$total = $model->where($map)->count();
		$page = new \Think\Page($total, $pageSize);
		$list = $model->where($map)->order('update_time desc')->limit($page->firstRow .',' . $page->listRows)->select();
		// echo $model->getLastsql();exit;
		$alist = array();
		$attchment=M('Attachment');
		foreach($list as $key => $val) {
			$alist[$key]['articleId'] = $val['id'];
			$alist[$key]['title'] = $val['title'];
			$alist[$key]['content'] = htmlspecialchars_decode($val['content']);
			$alist[$key]['createTime'] = $val['create_time'];
			$alist[$key]['status'] = $val['state'];
			$a=$attchment->where('type="image" and aid='.$val['id'])->order("sort ASC,attachid ASC")->find();
			if($a){
				$alist[$key]['fileUrl'] =  $hots . $a['thumb'] ;
				$alist[$key]['isImage'] = 1;
			}else{
				$alist[$key]['fileUrl'] =  '';
				$alist[$key]['isImage'] = 0;
			}
			$b=$attchment->where('type="video" and aid='.$val['id'])->find();
			if($b){
				$alist[$key]['fileUrl'] =  $hots . $b['thumb'] ;
				$alist[$key]['isVideo'] = 1;
			}else{
				$alist[$key]['isVideo'] = 0;
			}

		}

		if($alist) {
			$message['resultCode'] = 0;
			$message['message'] = '';
			$message['articles'] = $alist;
			$this->ajaxReturn($message);		
		} else {
			$message['resultCode'] = 0;
			$message['message'] = '未找到记录';
			$message['articles'] = array();
			$this->ajaxReturn($message);		
		}
	}


	/**
	 * 删除文稿
	 * @return [type] [description]
	 */
	public function delArticle() {
		apigetpost();
		$articleId = I('post.articleId');

		if(!$articleId) {
			$message['resultCode'] = 1;
			$message['message'] = '文稿ID未知';
			$this->ajaxReturn($message);
		}	

		$res = M('Article')->where(array('id' => $articleId, 'user_id' => $this->uid,	'state'=>array('in','-1,0,3')))->save(array('deletetime' => time(),'update_time'=>time()));//-1:撤回文稿，3：打回文稿
		if($res) {
			$imgs = M('Attachment')->where(array('aid' => $articleId, 'user_id' => $uid))->save(array('aid' => 0));
			$message['resultCode'] = 0;
			$message['message'] = '删除成功';
			$this->ajaxReturn($message);			
		} else {
			$message['resultCode'] = 1;
			$message['message'] = '删除失败';
			$this->ajaxReturn($message);

		}	
	} 

	/**
	 * 撤销文稿
	 * @return [type] [description]
	 */
	public function revocationArticle() {
		apigetpost();
		$articleId = I('post.articleId');
		if(!$articleId) {
			$message['resultCode'] = 1;
			$message['message'] = '文稿ID未知';
			$this->ajaxReturn($message);
		}	

		$res = M('Article')->where(array('id' => $articleId, 'user_id' => $this->uid))->save(array('state' => -1,'update_time'=>time()));
		if($res !== false) {
			$message['resultCode'] = 0;
			$message['message'] = '撤销成功';
			$this->ajaxReturn($message);		
		} else {
			$message['resultCode'] = 1;
			$message['message'] = '撤销失败';
			$this->ajaxReturn($message);			
		}
	}

	public function unRevocationArticle() {
		apigetpost();
		$articleId = I('post.articleId');
		if(!$articleId) {
			$message['resultCode'] = 1;
			$message['message'] = '文稿ID未知';
			$this->ajaxReturn($message);
		}	

		$res = M('Article')->where(array('id' => $articleId, 'user_id' => $this->uid))->save(array('state' => 0,'update_time'=>time()));
		if($res !== false) {
			$message['resultCode'] = 0;
			$message['message'] = '设置成功';
			$this->ajaxReturn($message);		
		} else {
			$message['resultCode'] = 1;
			$message['message'] = '设置失败';
			$this->ajaxReturn($message);			
		}
	}


protected function changeArticleStateByState($articleId,$orgi_state,$new_state){    
    $data['state']=$new_state; 
    $data['update_time']=time();
    $re=M('Article')->where(array(
        'id'=>$articleId,
        'state'=>$orgi_state
    ))->save($data);
    return ($re);
}

public function articleInfo(){
		// $userToken= I('get.userToken');	 //是	String	   用户登录的唯一标识
    	$articleId=I('get.articleId');  //是      int         文稿id
    	$author_id=$this->uid;	//用户ID
    	
        $hots=C('UPLOAD_HOST');
    	if($author_id){
    		if($articleId){
    			$map['id']=$articleId;
    			$article=M('Article')
                ->alias('ar')
                ->join('__CHANNEL__ ch ON ar.column_id=ch.chid','left')
                ->field("user_id createuserid,id articleId,verify_id,title,content,create_time createTime ,author reporters,state status,relation")
                ->where($map)->find();

                if($article){
                	$approve=unserialize($article['relation']);
                	if($article['createuserid']==$author_id || in_array($author_id,$approve[0])){                		                
	                    if(in_array($author_id,$approve[0])){
	                        $article['isApprove']=1;
	                        //点击详情修改文稿状态
	                        $res=$this->changeArticleStateByState($articleId,0,2);
	                       
	                        if($res){
	                        	$article['status']='2';
	                        }
	                    }else{	       
	                        $article['isApprove']=0;
	                    }
	                    unset($article['relation']);
                	}else{
            		    $article=array();
                    	$message['resultCode']="0";
						$message['message']="";
						$message['article']=$article;
						$this->ajaxReturn($message);
						exit();
                	}

                    $attchment=M('Attachment')->field("attachid fileId,CONCAT('{$hots}',filepath,filename) url,type fileType,sort,CONCAT('{$hots}',thumb) thumb,thumbwidth,thumbheight")->order('sort ASC')->where(array('aid'=>$articleId))->select();
                     foreach($attchment as $k=>$v){
                     	$attchment[$k]['fileType']=$v['filetype'];
                     	$attchment[$k]['thumbWidth']=$v['thumbwidth'];
                     	$attchment[$k]['thumbHeight']=$v['thumbheight'];
                     	unset($attchment[$k]['filetype']);
                     	unset($attchment[$k]['thumbwidth']);
                     	unset($attchment[$k]['thumbheight']);
                     }

                    /* $image = new \Think\Image();
                     $ch = curl_init();
                    foreach($attchment as $k=>$v){                 	
                    	curl_setopt($ch, CURLOPT_URL, "http://10.25.19.74:10085/Mapi/Article/getImageSize?url=".$attchment[$k]['thumburl']);
                    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                    	curl_setopt($ch, CURLOPT_HEADER, 0);
                    	$output = curl_exec($ch);
                    	$output = json_decode($output,true);

                    	if($output['resultCode']==1){
							unset($attchment[$k]);
                    	}else{
                    		
							$attchment[$k]['thumbWidth']=$output['attchment']['thumbWidth'];
							$attchment[$k]['thumbHeight']=$output['attchment']['thumbHeight'];
							
                    	}						
						unset($attchment[$k]['thumburl']);
                    }
                    curl_close($ch); */ 

                    $article['fileArray']= $attchment;
                    if($article['reporters']){
                    	 $map['uid']=array("in",$article['reporters']);
	                    $reporters=M('UserInfo')->field("uid,realname")->where($map)->select();
	                    $article['reportersIdAndNames']=$reporters;
                    }else{
                    	$article['reportersIdAndNames']=array();
                    }
                   
                }

                if($article['status'] == 1) {
                	$article['approver'] = M('UserInfo')->where(array('uid' => $article['verify_id']))->getField('realname');
                } elseif($article['status'] == 3) {
                	$article['approver'] = M('UserInfo')->where(array('uid' => $article['verify_id']))->getField('realname');
    				$info = M('ReturnReason')->field('details')
		    		        ->where(array('article_id' => $articleId))->order('reason_id desc')->find(); 
		    		$article['reason'] = $info['details'];            	
                }
                
    			$message['resultCode']="0";
				$message['message']="";
				$message['article']=$article;
    		}else{
    			$message['resultCode']="1";
				$message['message']='文稿ID未知';
    		}
    	}else{
    		$message['resultCode']="1";
			$message['message']='用户未登录';
    	}
    	//dump($message);
    	$this->ajaxReturn($message);
	}



/*    function untreadArticle(){
        $userToken= I('get.userToken');  //是    String     用户登录的唯一标识
        $articleId=I('get.articleId');  //是      int         文稿id
        $author_id=F($userToken);   //用户ID
        if($author_id){
            if($articleId){
                $data['state']=3; //3-退回文稿
                $re=M('Article')->where(array(
                    'user_id'=>$author_id,
                    'id'=>$articleId
                ))->save($data);
                if($re){
                    $message['resultCode']="0";
                    $message['message']='成功处理';
                }else{
                    $message['resultCode']="-1";
                    $message['message']='服务器错误';
                }
                
            }else{
                $message['resultCode']="1";
                $message['message']='文稿ID未知';
            }
        }else{
            $message['resultCode']="1";
            $message['message']='用户未登录';
        }
        $this->ajaxReturn($message);
    }*/


    /*public function approveArticle(){

    	apigetpost();
 		
        // $userToken= I('post.userToken');  //是    String     用户登录的唯一标识
        $articleId=I('post.articleId');  //是      int         文稿id
        $state=I('post.status');       //审核文稿状态  0-待审核 1-审核通过 2-审核中 3-退稿
        $strArr=array('待审核','审核通过','审核中','退稿');
        $author_id=$this->uid;   //用户ID
        if($author_id){
            if($articleId){
                if(isset($state) && in_array($state,array(0,1,2,3))){
                    $ar=$this->getArticleInfo($articleId);
                    if(in_array($author_id,$ar['relation'][0])){
	                	if($state == 3) {
	                		$reason = I('post.reason', '');
	                		if($reason) {
		                		$arr['details'] = $reason;
		                		$arr['article_id'] = $articleId;
		                		$arr['details'] = $reason;
		                		$arr['createtime'] = time();
		                		M('ReturnReason')->add($arr);	                			
	                		}
	                	}
                        $data['state']=$state; 
                        if(!in_array($state,array(1,3))) {
                        	$data['update_time']=time();
                        }

   					   	$data['verify_id'] = $this->uid;
                        $re=M('Article')->where(array(
                            'id'=>$articleId
                        ))->save($data);
                        if($re){
                        	if($state==1){
                        		$this->pushArticle($articleId); //审核通过后向M2O后台推送见微文稿
                        	}                        	
                            $message['resultCode']="0";
                            $message['message']="已设置为：".$strArr[$state];
                        }else{
                            $message['resultCode']="-1";
                            $message['message']='服务器错误';
                        }        
                    }else{
                        $message['resultCode']="1";
                        $message['message']='您不具有审核此文稿权限';
                    }
                }else{
                    $message['resultCode']="1";
                    $message['message']='未知的审核操作';
                }  
            }else{
                $message['resultCode']="1";
                $message['message']='文稿ID未知';
            }
        }else{
            $message['resultCode']="1";
            $message['message']='用户未登录';
        }
        $this->ajaxReturn($message);
    }*/

    /**
     * 只能操作待审核和审核中
     * @return [type] [description]
     */
	public function approveArticle(){

    	apigetpost();
 		
        // $userToken= I('post.userToken');  //是    String     用户登录的唯一标识
        $articleId=I('post.articleId');  //是      int         文稿id
        $state=I('post.status');       //审核文稿状态  0-待审核 1-审核通过 2-审核中 3-退稿
        $strArr=array(0 => '待审核', 2 => '审核中');
        $author_id=$this->uid;   //用户ID
        if($author_id){
            if($articleId){
                if(isset($state) && in_array($state,array(0,2))){
                    $ar=$this->getArticleInfo($articleId);
                    if(in_array($author_id,$ar['relation'][0])){
                        $data['state']=$state; 
                        $re=M('Article')->where(array(
                            'id'=>$articleId
                        ))->save($data);
                        if($re){                       	
                            $message['resultCode']="0";
                            $message['message']="已设置为：".$strArr[$state];
                        }else{
                            $message['resultCode']="-1";
                            $message['message']='服务器错误';
                        }        
                    }else{
                        $message['resultCode']="1";
                        $message['message']='您不具有审核此文稿权限';
                    }
                }else{
                    $message['resultCode']="1";
                    $message['message']='未知的审核操作';
                }  
            }else{
                $message['resultCode']="1";
                $message['message']='文稿ID未知';
            }
        }else{
            $message['resultCode']="1";
            $message['message']='用户未登录';
        }
        $this->ajaxReturn($message);
    }

    /**
     * 通过审核
     * @return [type] [description]
     */
	public function passArticle(){

    	apigetpost();
 		
        // $userToken= I('post.userToken');  //是    String     用户登录的唯一标识
        $articleId=I('post.articleId');  //是      int         文稿id
        $state=I('post.status');       //审核文稿状态  0-待审核 1-审核通过 2-审核中 3-退稿
        $author_id=$this->uid;   //用户ID
        if($author_id){
            if($articleId){
                if(isset($state) && $state == 1){
                    $ar=$this->getArticleInfo($articleId);
                    if(in_array($author_id,$ar['relation'][0])){
                        $data['state']=$state; 
                        $data['update_time']=time();
   					   	$data['verify_id'] = $this->uid;
                        $re=M('Article')->where(array(
                            'id'=>$articleId
                        ))->save($data);
                        if($re){
                        	// if($state==1){
                        		// $this->pushArticle($articleId); //审核通过后向M2O后台推送见微文稿
                        	// }                       	
                            $message['resultCode']="0";
                            $message['message']="已设置为：".$strArr[$state];
                        }else{
                            $message['resultCode']="-1";
                            $message['message']='服务器错误';
                        }        
                    }else{
                        $message['resultCode']="1";
                        $message['message']='您不具有审核此文稿权限';
                    }
                }else{
                    $message['resultCode']="1";
                    $message['message']='未知的审核操作';
                }  
            }else{
                $message['resultCode']="1";
                $message['message']='文稿ID未知';
            }
        }else{
            $message['resultCode']="1";
            $message['message']='用户未登录';
        }
        $this->ajaxReturn($message);
    }


    /**
     * 退稿
     * @return [type] [description]
     */
	public function returnedArticle(){

    	apigetpost();
 		
        // $userToken= I('post.userToken');  //是    String     用户登录的唯一标识
        $articleId=I('post.articleId');  //是      int         文稿id
        $state=I('post.status');       //审核文稿状态  0-待审核 1-审核通过 2-审核中 3-退稿
        $author_id=$this->uid;   //用户ID
        $reason = I('post.reason', '');
        if($author_id){
            if($articleId){
                if(isset($state) && $state == 3){
                	if($reason) {
	                    $ar=$this->getArticleInfo($articleId);
	                    if(in_array($author_id,$ar['relation'][0])){
	                        $data['state']=$state; 
	                        $data['update_time']=time();
	   					   	$data['verify_id'] = $this->uid;
	                        $re=M('Article')->where(array(
	                            'id'=>$articleId
	                        ))->save($data);
	                        if($re){  
		                		$arr['details'] = $reason;
		                		$arr['article_id'] = $articleId;
		                		$arr['details'] = $reason;
		                		$arr['user_id'] = $author_id;
		                		$arr['createtime'] = time();
		                		$r = M('ReturnReason')->add($arr);
		                		if(!$r) {
		                            $message['resultCode']="0";
		                            $message['message']="退稿原因写入失败";  
		                            $this->ajaxReturn($message);		                			
		                		}	                			

	                            $message['resultCode']="0";
	                            $message['message']="已设置为：".$strArr[$state];
	                        }else{
	                            $message['resultCode']="-1";
	                            $message['message']='服务器错误';
	                        }        
	                    }else{
	                        $message['resultCode']="1";
	                        $message['message']='您不具有审核此文稿权限';
	                    }
                    } else {
                      	$message['resultCode']="1";
                    	$message['message']="未填写退稿原因";                   	
                    }
                }else{
                    $message['resultCode']="1";
                    $message['message']='未知的审核操作';
                }  
            }else{
                $message['resultCode']="1";
                $message['message']='文稿ID未知';
            }
        }else{
            $message['resultCode']="1";
            $message['message']='用户未登录';
        }
        $this->ajaxReturn($message);
    }

    /**
     * 获取退稿原因
     * @return [type] [description]
     */
    public function getReasonByArticleId() {
    	apigetpost();
    	$articleId = I('post.articleId');
    	if($articleId) {
    		$info = M('ReturnReason')->alias('r')
    		        ->join('__USER_INFO__ AS ui ON r.user_id = ui.uid')
    		        ->field('r.*, ui.realname')
    		        ->where(array('article_id' => $articleId))->select();
    		if(!empty($info)) {
    			$message['data'] = $info;
	         	$message['resultCode'] = "0";
	            $message['message'] = ''; 	
    		} else {
	         	$message['resultCode'] = "1";
	            $message['message'] = '暂无记录'; 
    		} 		
    	} else {
          	$message['resultCode'] = "1";
            $message['message'] = '稿件不存在';  		
    	}
    	$this->ajaxReturn($message);
    }

    protected function getArticleInfo($id){
        $article=M('Article')
                ->alias('ar')
                ->join('__CHANNEL__ ch ON ar.column_id=ch.chid','left')
                ->where(array(
                    'id'=>$id
                ))->find();
        if($article){
             $approve=unserialize($article['relation']);                
            $article['relation']=$approve;
        }
        return $article;
    }


    function aaaa(){
    	$a=M('Attachment')->select();
    	$image=new \Think\Image();
    	foreach($a as $k=>$v){
    		//echo UPLOAD_PATH.$v['filepath'].$v['filename'];
    		if(is_file(UPLOAD_PATH.$v['filepath'].$v['filename']) && is_file(UPLOAD_PATH.$v['thumb'])){
    			$image->open(UPLOAD_PATH.$v['filepath'].$v['filename']);
				$a['oriheight']=$image->height();
				$a['oriwidth']=$image->width();
				$image->open(UPLOAD_PATH.$v['thumb']);
				$a['thumbheight']=$image->height();
				$a['thumbwidth']=$image->width();
				M('Attachment')->where('attachid='.$v['attachid'])->save($a);
    		}
    	}
    }

    function test(){
    	extension_loaded ( 'ffmpeg' );
    	echo $movefile = realpath('./Uploads')."/Video/2016/05/30/574b90d53aa78.wmv"; 
		$mov = new \ffmpeg_movie($movefile);
		 printf("file name = %s\n", $mov->getFileName()); 
    printf("duration = %s seconds\n", $mov->getDuration()); 
    printf("frame count = %s\n", $mov->getFrameCount()); 
    printf("frame rate = %0.3f fps\n", $mov->getFrameRate()); 
    printf("comment = %s\n", $mov->getComment()); 
    printf("title = %s\n", $mov->getTitle()); 
    printf("author = %s\n", $mov->getAuthor()); 
    printf("copyright = %s\n", $mov->getCopyright()); 
    printf("get bit rate = %d\n", $mov->getBitRate()); 
    printf("has audio = %s\n", $mov->hasAudio() == 0 ? 'No' : 'Yes'); 
    if ($mov->hasAudio()) { 
        printf("get audio stream id= %s\n", $mov->getAudioStreamId()); 
        printf("get audio codec = %s\n", $mov->getAudioCodec()); 
        printf("get audio bit rate = %d\n", $mov->getAudioBitRate()); 
        printf("get audio sample rate = %d \n", $mov->getAudioSampleRate()); 
        printf("get audio channels = %s\n", $mov->getAudioChannels()); 
    } 
    printf("has video = %s\n", $mov->hasVideo() == 0 ? 'No' : 'Yes'); 
    if ($mov->hasVideo()) { 
        printf("frame height = %d pixels\n", $mov->getFrameHeight()); 
        printf("frame width = %d pixels\n", $mov->getFrameWidth()); 
        printf("get video stream id= %s\n", $mov->getVideoStreamId()); 
        printf("get video codec = %s\n", $mov->getVideoCodec()); 
        printf("get video bit rate = %d\n", $mov->getVideoBitRate()); 
        printf("get pixel format = %s\n", $mov->getPixelFormat()); 
        printf("get pixel aspect ratio = %s\n", $mov->getPixelAspectRatio()); 
        $frame = $mov->getFrame(10); 
        printf("get frame = %s\n", is_object($frame) ? 'true' : 'false'); 
        printf("  get frame number = %d\n", $mov->getFrameNumber()); 
        printf("  get frame width = %d\n", $frame->getWidth()); 
        printf("  get frame height = %d\n", $frame->getHeight()); 
    } 
    echo "\n--------------------\n\n"; 


	  $f = $mov->getFrame(1);
	  $gd_image = $f->toGDImage();
	  $img="./Uploads/test.jpg";
	  imagejpeg($gd_image, $img);
	  imagedestroy($gd_image);

    }
}